#include "ff.h"
#include "fatfs.h"
#include "log.h"
#include "bsp_spiflash.h"

#include <stdio.h>
#include <string.h>

static const char *writeInfo = "Hello world\r\nHello world\r\nHello world\r\n";


FRESULT scan_files(
    char *path        /* Start node to be scanned (***also used as work area***) */
)
{
    FRESULT res;
    DIR dir;
    UINT i;
    static FILINFO fno;


    res = f_opendir(&dir, path);                       /* Open the directory */

    if(res == FR_OK)
    {
        for(;;)
        {
            res = f_readdir(&dir, &fno);                   /* Read a directory item */

            if(res != FR_OK || fno.fname[0] == 0)
            {
                break;    /* Break on error or end of dir */
            }

            if(fno.fattrib & AM_DIR)                       /* It is a directory */
            {
                //i = strlen(path);
                sprintf(path, "/%s", fno.fname);
                res = scan_files(path);                    /* Enter the directory */

                if(res != FR_OK)
                {
                    break;
                }

                path[i] = 0;
            }
            else                                           /* It is a file. */
            {
                LOG("%s%s\n", path, fno.fname);
            }
        }

        f_closedir(&dir);
    }

    return res;
}


void fatfs_test(void)
{
    uint32_t Identification;

    FRESULT fs_res;

    LOG("Hello, USB");

    Identification = SPI_FLASH_ReadID();

    LOG("ID:%X", Identification);
    
    fs_res = f_mount(&USERFatFS, "/", 1);
    
    LOG("f_mount: %d", fs_res);
    
    if(fs_res == FR_NO_FILESYSTEM)
    {
        fs_res = f_mkfs("", 1, 0);
        LOG("f_mkfs: %d", fs_res);
        fs_res = f_mount(&USERFatFS, "/", 1);
    }
    
    if(fs_res == FR_OK)
    {
        fs_res = f_open(&USERFile, "test.txt", FA_OPEN_ALWAYS | FA_WRITE);
        LOG("f_open: %d", fs_res);
        
        if(fs_res == FR_OK)
        {
            uint32_t bw;
            fs_res = f_write(&USERFile, writeInfo, strlen(writeInfo), &bw);
            LOG("f_write: %d, bw: %d", fs_res, bw);
            f_close(&USERFile);
        }
    }
    else
    {
        LOG("f_mount: %d", fs_res);
    }
    
    scan_files("/");
}

